//
//  PhotoViewController.swift
//  PhotoTestDemo
//
//  Created by 惠 on 2020/9/8.
//  Copyright © 2020 惠. All rights reserved.
//

import UIKit
import Photos

class PhotoViewController: UIViewController {
    
    let screenW = UIScreen.main.bounds.width
    let screenH = UIScreen.main.bounds.height
    
    //用来存放Cell的唯一标示符
    var cellDic: [String: String] = [:]
    
    ///取得的资源结果，用了存放的PHAsset
    var assetsFetchResults:PHFetchResult<PHAsset>?
    
    ///缩略图大小
    var assetGridThumbnailSize:CGSize!
    
    /// 带缓存的图片管理对象
    var imageManager:PHCachingImageManager!
    
    //选择代理
    var selectedHandler: (([PHAsset])-> Swift.Void)?
    var selectedFinishHandler: (([PHAsset])-> Swift.Void)?
    //选择内容
    var selectedAsset: [PHAsset] = []
    //最多选择图片数量
    var maxSelectPhotoCount: Int = 9
    //最多选择视频数量
    var maxSelectVideoCount: Int = 1
    //储存选中的下标
    var selectedIndex: [Int] = []
    //类型
    var type: SelectType = .defaults
    //颜色
    var colorType: ColorType = .defaults
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        //根据单元格的尺寸计算我们需要的缩略图大小
        let scale = UIScreen.main.scale
        let cellSize = (self.photoCollectionView.collectionViewLayout as! UICollectionViewFlowLayout).itemSize
        assetGridThumbnailSize = CGSize(width:cellSize.width*scale ,
                                        height:cellSize.height*scale)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(self, selector: #selector(imageCategoryAction(not:)), name: NSNotification.Name(rawValue: "imageCategory"), object: nil)
        
        setUI()
        albumsContent()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        photoCollectionView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: screenW, height: view.frame.height))
    }
    
    //MARK: -懒加载UI
    lazy var photoCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 5
        layout.minimumInteritemSpacing = 5
        layout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        layout.itemSize = CGSize(width: (screenW-25)/4, height: (screenW-25)/4)
        let photoCollectionView = UICollectionView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: screenW, height: screenH-140)), collectionViewLayout: layout)
        photoCollectionView.dataSource = self
        photoCollectionView.delegate = self
        photoCollectionView.backgroundColor = .white
        return photoCollectionView
    }()
    
    lazy var imageCategoryView = ImageCategoryView(colorType: colorType, frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: screenW, height: screenH-60)))
    
    //提示框
    let alertVC = UIAlertController(title: "", message: nil, preferredStyle: .alert)
    //定时器
    var timer: Timer?
    
    //MARK: -设置UI
    func setUI() {
        view.backgroundColor = .white
        
        view.addSubview(photoCollectionView)
        
        view.addSubview(imageCategoryView)
        imageCategoryView.isHidden = true
        imageCategoryView.alphaButton.addTarget(self, action: #selector(alphaButtonAction), for: .touchUpInside)
    }
    
    //MARK: -点击事件
    @objc func alphaButtonAction() {
        imageCategoryView.isHidden = true
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "bottonSelect"), object: self, userInfo: ["asset1": 1])
    }
    
    //MARK: -通知
    //选择相薄类型
    @objc func imageCategoryAction(not: Notification) {
        if let item = not.userInfo!["asset"] as? AlbumItem {
            assetsFetchResults = item.fetchResult
            self.photoCollectionView.reloadData()
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    //MARK: -相册列表
    func albumsContent() {
        //申请权限
        PHPhotoLibrary.requestAuthorization({ (status) in
            if status != .authorized {
                return
            }
            
            //获取所有资源
            let allPhotosOptions = PHFetchOptions()
            //按照创建时间倒序排列creationDate 创建时间   modificationDate 修改时间  location 位置信息 duration时长
            allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
            //只获取图片
            //            allPhotosOptions.predicate = NSPredicate(format: "mediaType = %d",
            //                                                     PHAssetMediaType.image.rawValue)
            //            self.assetsFetchResults = PHAsset.fetchAssets(with: PHAssetMediaType.image,
            //                                                          options: allPhotosOptions)
            //获取所有资源
            self.assetsFetchResults = PHAsset.fetchAssets(with: allPhotosOptions)
            // 初始化和重置缓存
            self.imageManager = PHCachingImageManager()
            self.resetCachedAssets()
            
            //collection view 重新加载数据
            DispatchQueue.main.async{ [weak self] in
                guard let self = self else { return }
                self.photoCollectionView.reloadData()
            }
        })
    }
    
    //重置缓存
    func resetCachedAssets(){
        self.imageManager.stopCachingImagesForAllAssets()
    }
    
}

//MARK: - UICollectionViewDataSource, UICollectionViewDelegate
extension PhotoViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.assetsFetchResults?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        var identifier = cellDic["\(indexPath)"]
        if identifier == nil {
            identifier = "PhotoCollectionViewCell\(indexPath)"
            cellDic["\(indexPath)"] = identifier
            photoCollectionView.register(PhotoCollectionViewCell.classForCoder(), forCellWithReuseIdentifier: identifier!)
        }
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier!, for: indexPath) as! PhotoCollectionViewCell
        cell.colorType = colorType
        if let asset = self.assetsFetchResults?[indexPath.row] {
            //获取缩略图
            self.imageManager.requestImage(for: asset, targetSize: assetGridThumbnailSize,
                                           contentMode: PHImageContentMode.aspectFill,
                                           options: nil) { (image, nfo) in
                                            
                                            cell.photoImage.image = image
            }
            if asset.mediaType.rawValue == 1 {
                cell.timeLabel.isHidden = true
            } else if asset.mediaType.rawValue == 2 {
                cell.timeLabel.isHidden = false
                cell.timeLabel.text = videoDuration(videoAsset: asset)
            }
        }
        var isSelectItem = false
        for index in selectedIndex {
            if index == indexPath.row {
                isSelectItem = true
            }
        }
        cell.selectButton.isSelected = isSelectItem
        cell.selectButton.tag = indexPath.item
        cell.selectButton.addTarget(self, action: #selector(selectButtonAction(sender:)), for: .touchUpInside)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let vc = ImageDetailViewController()
        vc.colorType = colorType
        vc.assetsFetchResults = assetsFetchResults
        vc.index = indexPath
        vc.maxSelectPhotoCount = maxSelectPhotoCount
        vc.maxSelectVideoCount = maxSelectVideoCount
        vc.selectedAsset = selectedAsset
        vc.selectedIndex = selectedIndex
        vc.type = type
        vc.selectedHandler = { [weak self] myAssets, selectIndexs in
            guard let self = self else { return }
            self.selectedAsset.removeAll()
            for myAsset in myAssets {
                self.selectedAsset.append(myAsset)
            }
            self.selectedIndex.removeAll()
            for selectIndex in selectIndexs {
                self.selectedIndex.append(selectIndex)
            }
            self.photoCollectionView.reloadData()
            self.selectedHandler?(self.selectedAsset)
        }
        vc.selectedFinishHandler = { [weak self] myAssets in
            guard let self = self else { return }
            self.selectedFinishHandler?(myAssets)
        }
        vc.modalPresentationStyle = .fullScreen
        self.present(vc, animated: true, completion: nil)
    }
    
    //获取视频时间
    func videoDuration(videoAsset: PHAsset?) -> String {
        guard let asset = videoAsset else { return "00:00" }
        let duration: TimeInterval = asset.duration
        let s: Int = Int(duration) % 60
        let m: Int = Int(duration) / 60
        let formattedDuration = String(format: "%02d:%02d ", m, s)
        return formattedDuration
    }
    
    //选中事件
    @objc func selectButtonAction(sender: UIButton) {
        let myAsset = self.assetsFetchResults?[sender.tag]
        var sameIndex: Bool = false
        var removeI = 0
        var i = 0
        for index in selectedIndex {
            if index == sender.tag {
                sameIndex = true
                removeI = i
            }
            i += 1
        }
        
        if sameIndex {
            //删除相同数据
            selectedIndex.remove(at: removeI)
            sender.isSelected = false
            selectedAsset.remove(at: removeI)
            self.selectedHandler?(selectedAsset)
        } else {
            if selectedAsset.count == 0 {
                if type == .photo {
                    if myAsset?.mediaType.rawValue == 1 {
                        selectedIndex.append(sender.tag)
                        sender.isSelected = true
                        selectedAsset.append(myAsset!)
                        self.selectedHandler?(selectedAsset)
                    } else {
                        DispatchQueue.main.async {[weak self] in
                            guard let self = self else {return}
                            //不同类型
                            self.alertVC.title = "暂不支持视频格式"
                            self.present(self.alertVC, animated: true, completion: nil)
                            self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.hiddenAlert), userInfo: nil, repeats: false)
                        }
                    }
                } else if type == .picture {
                    if myAsset?.mediaType.rawValue == 2 {
                        selectedIndex.append(sender.tag)
                        sender.isSelected = true
                        selectedAsset.append(myAsset!)
                        self.selectedHandler?(selectedAsset)
                    } else {
                        DispatchQueue.main.async {[weak self] in
                            guard let self = self else {return}
                            //不同类型
                            self.alertVC.title = "暂只支持视频格式"
                            self.present(self.alertVC, animated: true, completion: nil)
                            self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.hiddenAlert), userInfo: nil, repeats: false)
                        }
                    }
                } else {
                    selectedIndex.append(sender.tag)
                    sender.isSelected = true
                    selectedAsset.append(myAsset!)
                    self.selectedHandler?(selectedAsset)
                }
            } else {
                let asset = selectedAsset[0]
                //照片
                if asset.mediaType.rawValue == 1 {
                    if selectedAsset.count < maxSelectPhotoCount {
                        if asset.mediaType == myAsset?.mediaType {
                            selectedIndex.append(sender.tag)
                            sender.isSelected = true
                            selectedAsset.append(myAsset!)
                            self.selectedHandler?(selectedAsset)
                        } else {
                            DispatchQueue.main.async {[weak self] in
                                guard let self = self else {return}
                                //不同类型
                                self.alertVC.title = "暂不支持视频格式"
                                self.present(self.alertVC, animated: true, completion: nil)
                                self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.hiddenAlert), userInfo: nil, repeats: false)
                            }
                            
                        }
                    } else {
                        DispatchQueue.main.async {[weak self] in
                            guard let self = self else {return}
                            self.alertVC.title = "最多选\(self.maxSelectPhotoCount)张"
                            self.present(self.alertVC, animated: true, completion: nil)
                            self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.hiddenAlert), userInfo: nil, repeats: false)
                        }
                    }
                } else if asset.mediaType.rawValue == 2 {
                    //视频
                    if selectedAsset.count < maxSelectVideoCount {
                        if asset.mediaType == myAsset?.mediaType {
                            selectedIndex.append(sender.tag)
                            sender.isSelected = true
                            selectedAsset.append(myAsset!)
                            self.selectedHandler?(selectedAsset)
                        } else {
                            DispatchQueue.main.async {[weak self] in
                                guard let self = self else {return}
                                //不同类型
                                self.alertVC.title = "暂只支持视频格式"
                                self.present(self.alertVC, animated: true, completion: nil)
                                self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.hiddenAlert), userInfo: nil, repeats: false)
                            }
                        }
                    } else {
                        DispatchQueue.main.async {[weak self] in
                            guard let self = self else {return}
                            self.alertVC.title = "最多选\(self.maxSelectVideoCount)张"
                            self.present(self.alertVC, animated: true, completion: nil)
                            self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.hiddenAlert), userInfo: nil, repeats: false)
                        }
                    }
                }
            }
        }
        
    }
    
    //提示框
    @objc func hiddenAlert() {
        alertVC.dismiss(animated: true, completion: nil)
        
        timer?.invalidate()
        timer = nil
    }
}
